package com.wanli.storemobile.utils;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;


import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wanli.storemobile.MyApplication;
import com.wanli.storemobile.appconst.Constants;
import com.wanli.storemobile.widget.CommonDialog;

import java.util.ArrayList;
import java.util.List;


/**
 * Time: 2019/7/25
 * Author: ZF
 * Description:
 * 1、检查权限
 * 2、请求单个权限
 * 3、请求多个权限 返回一个结果，（所有权限都被给予的时候 返回 true 否则返回false）
 * 4、请求多个权限 并且分别获取权限申请结果
 */

public class PermissionsManager {

    private OnPermissionResultListener resultListener;
    private List<String> rejectList;
    private FragmentActivity activity;
    private RxPermissions rxPermissions;
    private CommonDialog.Builder dialogBuild;
    private int permissionsBackNum = 0;
    private int permissionsNum = 0;

    public PermissionsManager(FragmentActivity activity) {
        this.activity = activity;
        rxPermissions = new RxPermissions(activity);
    }

    public void setResultListener(OnPermissionResultListener resultListener) {
        this.resultListener = resultListener;
    }

    public static boolean checkPermissions(String... permissions) {
        if (permissions == null || permissions.length == 0) {
            return false;
        }
        for (String permission : permissions) {
            if (!checkPermissions(permission)) {
                return false;
            }
        }
        return true;
    }

    public static boolean checkPermissions(String permission) {
        if (TextUtils.isEmpty(permission)) {
            return false;
        }
        //检查代码是否拥有这个权限
        int checkResult = ContextCompat.checkSelfPermission(MyApplication.getContext(), permission);
        return checkResult == PackageManager.PERMISSION_GRANTED;
    }


    //=====请求权限
    public void requestPermissionsEach(@NonNull String... permissions) {

        permissionsNum = permissions.length;
        permissionsBackNum = 0;
        if (rejectList == null) {
            rejectList = new ArrayList<>();
        } else {
            rejectList.clear();
        }

        rxPermissions.requestEach(permissions)//
                .subscribe(permission -> {
                    permissionsBackNum++;
                    String name = permission.name;
                    String s = permission.toString();
                    if (!permission.granted) {//用户同意该权限
                        rejectList.add(name);//拒绝的权限，
                    }
                    if (permissionsBackNum == permissionsNum && resultListener != null) {
                        boolean flag = false;
                        if (rejectList == null || rejectList.size() == 0) {
                            flag = true;
                        }
                        resultListener.permissionResult(flag, rejectList);
                    }
                });
    }

    private void skipToPermissionSetting(FragmentActivity activity) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
        intent.setData(uri);
        activity.startActivityForResult(intent, Constants.PERMISSION_REQUEST_CODE);
    }


    public void showDialog() {
        dialogBuild = new CommonDialog.Builder(activity);
        dialogBuild.setTitle("权限被禁用");
        dialogBuild.setMessage("权限被禁用，导致APP功能无法正常使用，是否重新开启权限");
        dialogBuild.setPositiveButton("确定", v -> {
            dialogBuild.dismiss();
            skipToPermissionSetting(activity);

        });

        dialogBuild.setNegativeButton("取消", v -> dialogBuild.dismiss());
        dialogBuild.setCancelable(false);
        dialogBuild.show();

    }

    public interface OnPermissionResultListener {
        void permissionResult(boolean allGranted, List<String> rejectPermissionList) throws Exception;
    }
}
